package org.aynu.orderservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aynu.orderservice.common.OrderConstants;
import org.aynu.orderservice.common.OrderResponse;
import org.aynu.orderservice.entity.OrderEntity;
import org.aynu.orderservice.entity.OrderItemsEntity;
import org.aynu.orderservice.feign.CartServiceClient;
import org.aynu.orderservice.feign.ProductServiceClient;
import org.aynu.orderservice.mapper.OrderItemsMapper;
import org.aynu.orderservice.mapper.OrderMapper;
import org.aynu.orderservice.service.OrderService;
import org.aynu.productservice.common.ProductResponse;
import org.aynu.cartservice.common.CartResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单服务实现 - 完整功能版
 *
 * @author 小粥
 * @since 2025/03/03
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {
    private final OrderItemsMapper orderItemsMapper;
    private final CartServiceClient cartServiceClient;
    private final ProductServiceClient productServiceClient;

    @Autowired
    public OrderServiceImpl(OrderItemsMapper orderItemsMapper, CartServiceClient cartServiceClient, ProductServiceClient productServiceClient) {
        this.orderItemsMapper = orderItemsMapper;
        this.cartServiceClient = cartServiceClient;
        this.productServiceClient = productServiceClient;
    }

    /**
     * 从购物车创建订单
     */
    @Override
    public OrderResponse<Integer> createOrder(OrderEntity orderEntity, List<OrderItemsEntity> orderItemsEntities, Integer cartId) {
        try {
            log.info("开始创建订单: userId={}, cartId={}", orderEntity.getUserId(), cartId);
            if (orderEntity == null || orderItemsEntities == null || orderItemsEntities.isEmpty()) {
                return OrderResponse.error("订单参数无效");
            }
            if (cartId == null || cartId <= 0) {
                return OrderResponse.error("购物车ID无效");
            }

            OrderResponse<Integer> response = saveOrderAndItems(orderEntity, orderItemsEntities);
            if (!response.isSuccess()) {
                return response;
            }

            log.info("订单创建成功，准备清理购物车: orderId={}", orderEntity.getOrderId());
            List<Integer> productIds = orderItemsEntities.stream()
                    .map(OrderItemsEntity::getProductId)
                    .collect(Collectors.toList());
            CartResponse<String> cartResponse = cartServiceClient.deleteItemFromCart(new HashMap<String, Object>() {{
                put("userId", orderEntity.getUserId());
                put("productId", productIds.get(0)); // 只删除第一个商品
            }});
            if (!cartResponse.isSuccess()) {
                log.warn("从购物车删除商品失败: userId={}, productIds={}, message={}",
                        orderEntity.getUserId(), productIds, cartResponse.getMessage());
            } else {
                log.info("购物车清理成功: userId={}, productIds={}", orderEntity.getUserId(), productIds);
            }

            return response;
        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 直接创建订单
     */
    @Override
    public OrderResponse<Integer> directCreateOrder(OrderEntity orderEntity, List<OrderItemsEntity> orderItemsEntities) {
        try {
            // 输入校验
            if (orderEntity == null || orderItemsEntities == null || orderItemsEntities.isEmpty()) {
                return OrderResponse.error("订单参数无效");
            }

            return saveOrderAndItems(orderEntity, orderItemsEntities);
        } catch (Exception e) {
            log.error("直接创建订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 保存订单和订单项到数据库
     */
    private OrderResponse<Integer> saveOrderAndItems(OrderEntity orderEntity, List<OrderItemsEntity> orderItemsEntities) {
        // 库存检查
        for (OrderItemsEntity item : orderItemsEntities) {
            ProductResponse<Integer> stockResponse = productServiceClient.getProductStock(
                    Collections.singletonMap("productId", item.getProductId()));
            if (!stockResponse.isSuccess()) {
                return OrderResponse.error("库存检查失败: " + stockResponse.getMessage());
            }
            if (stockResponse.getData() < item.getQuantity()) {
                return OrderResponse.error("商品库存不足: productId=" + item.getProductId());
            }
        }

        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItemsEntity item : orderItemsEntities) {
            BigDecimal itemTotal = item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
            totalAmount = totalAmount.add(itemTotal);
        }
        orderEntity.setTotalAmount(totalAmount);
        orderEntity.setStatus(OrderConstants.STATUS_WAIT_PAY);
        orderEntity.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        orderEntity.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

        // 保存订单
        log.info("尝试保存订单: {}", orderEntity);
        boolean orderSaved = this.save(orderEntity);
        if (!orderSaved) {
            log.error("订单保存失败: {}", orderEntity);
            return OrderResponse.error("订单保存失败");
        }
        log.info("订单保存成功，订单ID: {}", orderEntity.getOrderId());

        // 保存订单项并更新库存
        for (OrderItemsEntity item : orderItemsEntities) {
            item.setOrderId(orderEntity.getOrderId());
            log.info("尝试保存订单项: {}", item);
            int rows = orderItemsMapper.insert(item);
            if (rows <= 0) {
                log.error("订单项保存失败: {}", item);
                throw new RuntimeException("订单项保存失败");
            }
            log.info("订单项保存成功，订单项ID: {}", item.getOrderItemId());

            Map<String, Object> map2 = Map.of("productId", item.getProductId(), "quantity", -item.getQuantity());
            ProductResponse<Integer> stockUpdate = productServiceClient.updateProductStock(map2);
            System.out.println("更新库存响应码为："+ stockUpdate.getCode());
            if (!stockUpdate.isSuccess()) {
                log.error("库存更新失败: productId={}, message={}", item.getProductId(), stockUpdate.getMessage());
                throw new RuntimeException("库存更新失败: " + stockUpdate.getMessage());
            }
        }

        return OrderResponse.success(OrderConstants.SUCCESS_CREATE_ORDER, orderEntity.getOrderId());
    }

    /**
     * 按用户 ID 查询订单
     */
    @Override
    public OrderResponse<List<Map<String, Object>>> selectOrdersByUserId(Integer userId) {
        if (userId == null || userId <= 0) {
            return OrderResponse.error("用户ID无效");
        }

        List<OrderEntity> orders = list(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getUserId, userId));
        if (orders.isEmpty()) {
            return OrderResponse.success("无订单", Collections.emptyList());
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (OrderEntity order : orders) {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("order", order);

            List<OrderItemsEntity> items = orderItemsMapper.selectList(new LambdaQueryWrapper<OrderItemsEntity>()
                    .eq(OrderItemsEntity::getOrderId, order.getOrderId()));
            orderMap.put("orderItems", items);

            result.add(orderMap);
        }

        return OrderResponse.success("查询订单成功", result);
    }

    /**
     * 按订单 ID 查询订单
     */
    @Override
    public OrderResponse<Map<String, Object>> selectOrderById(Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return OrderResponse.error("订单ID无效");
        }

        OrderEntity order = getOne(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderId, orderId));
        if (order == null) {
            return OrderResponse.error("订单不存在");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("order", order);

        List<OrderItemsEntity> items = orderItemsMapper.selectList(new LambdaQueryWrapper<OrderItemsEntity>()
                .eq(OrderItemsEntity::getOrderId, orderId));
        result.put("orderItems", items);

        return OrderResponse.success("查询订单成功", result);
    }

    /**
     * 更新订单状态
     */
    @Override
    public OrderResponse<Integer> updateOrderStatus(Integer orderId, String status) {
        if (orderId == null || orderId <= 0) {
            return OrderResponse.error("订单ID无效");
        }
        if (status == null || status.isEmpty()) {
            return OrderResponse.error("状态无效");
        }

        OrderEntity order = getOne(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderId, orderId));
        if (order == null) {
            return OrderResponse.error("订单不存在");
        }

        order.setStatus(status);
        order.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        boolean updated = updateById(order);
        if (!updated) {
            return OrderResponse.error("更新订单状态失败");
        }

        return OrderResponse.success("订单状态更新成功", orderId);
    }

    /**
     * 用户取消订单
     */
    @Override
    public OrderResponse<Integer> cancelOrderByUser(Integer orderId, Integer userId) {
        if (orderId == null || orderId <= 0 || userId == null || userId <= 0) {
            return OrderResponse.error("订单ID或用户ID无效");
        }

        OrderEntity order = getOne(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderId, orderId));
        if (order == null) {
            return OrderResponse.error("订单不存在");
        }
        if (order.getUserId() != userId) {
            return OrderResponse.error("无权限取消订单");
        }

        order.setStatus(OrderConstants.STATUS_CANCELLED);
        order.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        boolean updated = updateById(order);
        if (!updated) {
            return OrderResponse.error("取消订单失败");
        }

        List<OrderItemsEntity> items = orderItemsMapper.selectList(new LambdaQueryWrapper<OrderItemsEntity>()
                .eq(OrderItemsEntity::getOrderId, orderId));
        for (OrderItemsEntity item : items) {
            ProductResponse<Integer> stockUpdate = productServiceClient.updateProductStock(new HashMap<String, Object>() {{
                put("productId", item.getProductId());
                put("quantity", item.getQuantity()); // 恢复库存
            }});
            if (stockUpdate.isSuccess()) {
                log.warn("库存恢复失败: productId={}, message={}", item.getProductId(), stockUpdate.getMessage());
            }
        }

        return OrderResponse.success("用户取消订单成功", orderId);
    }

    /**
     * 系统取消订单
     */
    @Override
    public OrderResponse<Integer> cancelOrderBySystem(Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return OrderResponse.error("订单ID无效");
        }

        OrderEntity order = getOne(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderId, orderId));
        if (order == null) {
            return OrderResponse.error("订单不存在");
        }

        order.setStatus(OrderConstants.STATUS_CANCELLED);
        order.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        boolean updated = updateById(order);
        if (!updated) {
            return OrderResponse.error("取消订单失败");
        }

        List<OrderItemsEntity> items = orderItemsMapper.selectList(new LambdaQueryWrapper<OrderItemsEntity>()
                .eq(OrderItemsEntity::getOrderId, orderId));
        for (OrderItemsEntity item : items) {
            ProductResponse<Integer> stockUpdate = productServiceClient.updateProductStock(new HashMap<String, Object>() {{
                put("productId", item.getProductId());
                put("quantity", item.getQuantity()); // 恢复库存
            }});
            if (!stockUpdate.isSuccess()) {
                log.warn("库存恢复失败: productId={}, message={}", item.getProductId(), stockUpdate.getMessage());
            }
        }

        return OrderResponse.success("系统取消订单成功", orderId);
    }
}